package com.you.atlas.web.member.module.action;

import java.io.IOException;

import org.apache.commons.fileupload.FileItem;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.citrus.service.form.Group;
import com.alibaba.citrus.turbine.Context;
import com.alibaba.citrus.turbine.Navigator;
import com.alibaba.citrus.turbine.TurbineRunData;
import com.alibaba.citrus.turbine.dataresolver.FormGroup;
import com.alibaba.citrus.turbine.dataresolver.Param;
import com.you.atlas.biz.member.constant.MemberRegisteFailture;
import com.you.atlas.biz.member.constant.MemberRegisteVO;
import com.you.atlas.biz.member.service.MemberService;
import com.you.common.file.ImageService;
import com.you.common.result.ServiceResult;
import com.you.common.webx.AuthContext;
import com.you.member.dal.dao.dataobject.MemberDO;

public class MemberAction {

    @Autowired
    private MemberService memberService;

    @Autowired
    private ImageService  imageService;

    public void doUploadFace(@FormGroup("uploadFace") Group group, Context context) {
        FileItem fileItem = group.getField("imgUrl").getFileItem();
        if (fileItem != null) {
            try {
                String faceImgUrl = imageService.scaleIcon(fileItem.getInputStream(), fileItem.getName(), 115, 115);
                String faceIconUrl = imageService.scaleIcon(faceImgUrl, 48, 48);
                context.put("faceImgUrl", faceImgUrl);
                context.put("faceIconUrl", faceIconUrl);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void doSetPassword(@FormGroup("setPassword") MemberRegisteVO memberRegisteVO, Context context,
                              Navigator navigator) {

        ServiceResult<MemberRegisteFailture> result = memberService.setPassword(AuthContext.getContext().getMemberId(),
                                                                                memberRegisteVO);
        if (result.isSuccess()) {
            navigator.redirectTo("memberModule").withTarget("me.vm");
        } else {
            context.put("result", result);
        }
    }

    public void doSaveFace(TurbineRunData rundata, @Param("faceImgUrl") String faceThumbUrl,
                           @Param("faceIconUrl") String faceIconUrl, Navigator navigator) {
        memberService.modifyMemberFace(AuthContext.getContext().getMemberId(), faceThumbUrl, faceIconUrl);
        navigator.redirectTo("memberModule").withTarget("me.vm");
    }

    public void doModify(@FormGroup("modifyMember") Group group, Context context, Navigator navigator) {
        MemberDO memberDO = new MemberDO();
        group.setProperties(memberDO);
        memberDO.setId(AuthContext.getContext().getMemberId());
        if (memberService.modify(memberDO)) {
            navigator.redirectTo("memberModule").withTarget("me.vm");
        }
    }

}
